import { HttpParams } from '@angular/common/http';
import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { STComponent } from '@delon/abc/st';
import { _HttpClient, ModalHelper, SettingsService } from '@delon/theme';
import { ModalHelperOptions } from '@delon/theme/src/services/modal/modal.helper';
import format from 'date-fns/format';
import * as moment from 'moment';
import { NzMessageService } from 'ng-zorro-antd/message';

import { dateChange } from '../../../shared/utils/date';
import { BusinessOrderOnPurchaseComponent } from './on-purchase/on-purchase.component';
import { BusinessOrderOrderProcessComponent } from './order-process/order-process.component';
import { BusinessOrderSetPurchaseEditComponent } from './set-purchase-edit/set-purchase-edit.component';
import { BusinessOrderSetPurchaseComponent } from './set-purchase/set-purchase.component';
import { BusinessOrderViewComponent } from './view/view.component';

@Component({
  selector: 'app-business-order',
  templateUrl: './order.component.html'
})
export class BusinessOrderComponent implements OnInit {
  @ViewChild('st') private readonly st!: STComponent;
  isAdmin = false;
  isShow = false;
  company_id = 0;
  statusNotice = {
    '3': { index: 3, text: '已发货', notice: '配送中', color: 'blue' },
    '5': { index: 5, text: '交易成功', notice: '订单完成', color: 'green' },
    '6': { index: 6, text: '已拒签', notice: '', color: '#f50' },
    '7': { index: 7, text: '已拒签', notice: '', color: '#f50' },
    '8': { index: 8, text: '待补货', notice: '确保 Fordeal 仓库在 7 天内有足够库存发货', color: 'orange' },
    '9': { index: 9, text: '补货中', notice: '卖家发货至 Fordeal 履约仓途中', color: 'gold' },
    '10': { index: 10, text: '处理中', notice: '订单库存已匹配，Fordeal 履约仓处理中，即将发出', color: 'cyan' },
    '99': { index: 99, text: '已取消', notice: '', color: 'red' }
  };
  sku_type = [
    { index: 'skuId', text: 'Fordeal SKU', checked: true },
    { index: 'skuNo', text: '商家SKU' },
    { index: 'itemId', text: '商品ID' },
    { index: 'itemNo', text: '商品货号' }
  ];
  url = `api/orders`;
  total = 0;
  pi = 1;
  ps = 30;
  loading = true;
  listOfData = [];
  today = new Date();
  defaultPlacedOrderAt = dateChange(-90, this.today);
  // defaultReadiedAt = dateChange(-7, new Date());
  placedOrderAt = [this.defaultPlacedOrderAt, this.today];
  readiedAt = [];
  ranges = { 今天: [new Date(), new Date()] };
  shops = [];
  shopMap = {};
  shopMapFull = {};
  companyMapFull = {};
  q: {
    orderSn: string;
    skuType: string;
    skuTypeValue: string;
    overTime: number;
    deliverPlaceCode: string;
    overTimeMark: number;
    cancelMark: number;
    shopId: number;
    companyId: number;
    status: number;
    placedOrderAtS: string;
    placedOrderAtE: string;
    readiedAtS: string;
    readiedAtE: string;
    countDown: number;
    title: string;
  } = {
    orderSn: '',
    skuType: 'skuId',
    overTimeMark: -1,
    cancelMark: -1,
    deliverPlaceCode: '',
    overTime: 0,
    skuTypeValue: '',
    shopId: 0,
    companyId: 0,
    status: 0,
    placedOrderAtS: '',
    placedOrderAtE: '',
    readiedAtS: '',
    readiedAtE: '',
    countDown: 0,
    title: ''
  };
  countDownOptions = [
    { val: 1, label: '1小时' },
    { val: 3, label: '3小时' },
    { val: 6, label: '6小时' },
    { val: 12, label: '12小时' },
    { val: 24, label: '24小时' },
    { val: 48, label: '48小时' }
  ];
  statusCount = {};
  placesMap = {};
  companyList = [];

  constructor(
    private http: _HttpClient,
    private msgSrv: NzMessageService,
    private modal: ModalHelper,
    private cdr: ChangeDetectorRef,
    private settingService: SettingsService
  ) {
    this.company_id = this.settingService.user.company_id;
    //console.log(this.settingService.user.ID);
    if (this.settingService.user.ID == 1) {
      this.isAdmin = true;
    }
    this.loadCompanies();
    this.loadShops();
    this.loadPlace();
  }

  place = [];

  loadPlace(shopId = 0): void {
    let params = new HttpParams().append('shopId', shopId);
    this.http.get(`api/places`, params).subscribe(res => {
      this.place = res.data;
      for (let i = 0; i < this.place.length; i++) {
        let pl = this.place[i];
        this.placesMap[pl['deliverPlaceCode']] = pl['deliverPlaceDesc'];
      }
    });
  }

  loadCompanies(): void {
    this.http.get(`api/company_map`).subscribe(res => {
      this.companyList = res.data;
      if (this.companyList.length > 1) {
        this.isShow = true;
      }
    });
  }

  loadShops(companyID = 0): void {
    this.http.get(`api/shop_map`, { companyId: companyID }).subscribe(res => {
      this.shops = res.data['shops'];
      for (let i = 0; i < res.data['shops'].length; i++) {
        // @ts-ignore
        this.shopMap[this.shops[i]['shop_id']] = this.shops[i]['fordeal_shop_name'];
      }
    });
    this.http.get(`api/shop_map_full`, { companyId: companyID }).subscribe(res => {
      this.shops = res.data['shops'];
      for (let i = 0; i < this.shops.length; i++) {
        // @ts-ignore
        this.shopMapFull[this.shops[i]['shop_id']] = this.shops[i]['fordeal_shop_name'];
        this.companyMapFull[this.shops[i]['shop_id']] = this.shops[i]['company_name'];
      }
    });
  }

  loadStatusCount(): void {
    this.http.get(`api/order/status_count`, this.q).subscribe(res => {
      this.statusCount = res.data;
    });
  }

  ngOnInit(): void {
    this.q.placedOrderAtS = format(this.placedOrderAt[0], 'yyyy-MM-dd');
    this.q.placedOrderAtE = format(this.placedOrderAt[1], 'yyyy-MM-dd');
    this.loadStatusCount();
    this.loadDataFromServer(this.pi, this.ps, this.q);
    this.cdr.detectChanges();
  }

  loadDataFromServer(pageIndex: number, pageSize: number, s_params: any): void {
    this.loading = true;
    let params = new HttpParams().append('pi', `${pageIndex}`).append('ps', `${pageSize}`).appendAll(s_params);
    this.http.get(`${this.url}`, params).subscribe(res => {
      if (res.err_code != 0) {
        this.msgSrv.error(res.msg);
      }
      this.total = res.data.total;
      // 处理倒计时
      this.listOfData = res.data.list;
      if (this.listOfData) {
        for (let i = 0; i < this.listOfData.length; i++) {
          // @ts-ignore
          this.listOfData[i]['deadline'] = moment(this.listOfData[i]['paymentAt']).add(5, 'days');
        }
      }
      this.loading = false;
    });
  }

  pageIndexChange(pageIndex: number): void {
    this.loadDataFromServer(pageIndex, this.ps, this.q);
  }

  pageSizeChange(pageSize: number): void {
    this.loadDataFromServer(this.pi, pageSize, this.q);
  }

  search(): void {
    this.pi = 1;
    this.ps = 30;
    this.loadStatusCount();
    this.loadDataFromServer(this.pi, this.ps, this.q);
  }

  view(shopId: number, orderSn: string): void {
    let options: ModalHelperOptions = {
      size: 'xl'
    };
    this.modal.createStatic(BusinessOrderViewComponent, { i: { shopId: shopId, orderSn: orderSn } }, options).subscribe(() => {
      this.st.reload();
    });
  }

  //编辑进度（订单进度）
  order_process(shopId: number, orderSn: string, orderId: string): void {
    console.log(shopId, orderSn);
    //return;
    let options: ModalHelperOptions = {
      size: 'lg'
    };
    this.modal
      .createStatic(
        BusinessOrderOrderProcessComponent,
        { i: { shopId: shopId, orderSn: orderSn, orderId: orderId, pcdr: this.cdr, pobj: this } },
        options
      )
      .subscribe(() => {
        this.st.reload();
      });
  }

  //设置采购
  set_purchase(shopId: number, orderSn: string, orderId: string, itemId: string, skuId: string): void {
    console.log(shopId, orderSn, itemId, skuId);
    return;
    let options: ModalHelperOptions = {
      size: 'lg'
    };
    this.modal
      .createStatic(
        BusinessOrderSetPurchaseComponent,
        { i: { shopId: shopId, orderSn: orderSn, orderId: orderId, itemId: itemId, skuId: skuId } },
        options
      )
      .subscribe(() => {
        this.st.reload();
      });
  }

  //一键采购
  on_purchase(shopId: number, orderSn: string, orderId: string, itemId: string, skuId: string): void {
    console.log(shopId, orderSn, itemId, skuId);
    return;
    let options: ModalHelperOptions = {
      size: 'lg'
    };
    this.modal
      .createStatic(
        BusinessOrderOnPurchaseComponent,
        { i: { shopId: shopId, orderSn: orderSn, orderId: orderId, itemId: itemId, skuId: skuId } },
        options
      )
      .subscribe(() => {
        this.st.reload();
      });
  }

  correctDatetime(value: any) {
    if (value) {
      value = value.replace('T', ' ').replace('Z', '');
      var timezoneOffset = new Date().getTimezoneOffset(); // 获取当前时区, 返回当前时区与UTC相差的分钟数
      var correct_ts = new Date(value).getTime() - timezoneOffset * 60 * 1000;
      var date = new Date(correct_ts);
      let Y = date.getFullYear(),
        M = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1,
        D = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate(),
        h = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours(),
        m = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes(),
        s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds();
      value = `${Y}-${M}-${D} ${h}:${m}:${s}`;
    }
    return value;
  }

  // 下单时间
  placedOrderAtChange($event: any) {
    this.q.placedOrderAtS = format($event[0], 'yyyy-MM-dd');
    this.q.placedOrderAtE = format($event[1], 'yyyy-MM-dd');
  }

  // 库存匹配时间
  readiedAtChange($event: any) {
    this.q.readiedAtS = format($event[0], 'yyyy-MM-dd');
    this.q.readiedAtE = format($event[1], 'yyyy-MM-dd');
  }

  tabSelect(value: any): void {
    this.q.status = value;
    this.pi = 1;
    this.ps = 30;
    this.loadDataFromServer(this.pi, this.ps, this.q);
  }

  shopChange(shopId: number) {
    this.loadPlace(shopId);
  }

  export() {
    this.http.get(`api/order/export`, this.q, { responseType: 'blob' }).subscribe(res => {
      if (res.type == 'application/json') {
        res.text().then((jsonResp: string) => {
          let js = JSON.parse(jsonResp);
          this.msgSrv.error(js.msg);
        });
        return;
      }
      let file = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      let fileURL = URL.createObjectURL(file);
      window.open(fileURL);
    });
  }

  companyChange(companyID: number) {
    this.loadShops(companyID);
    this.cdr.detectChanges();
  }

  getTime(timestamp: string) {
    if (timestamp && timestamp != '') {
      var date = new Date(parseInt(timestamp) * 1000);
      let Y = date.getFullYear(),
        M = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1,
        D = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate(),
        h = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours(),
        m = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes(),
        s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds();
      timestamp = `${Y}-${M}-${D} ${h}:${m}:${s}`;
    }
    return timestamp;
  }
}
